package com.xk.sport.backend.service;

import com.google.common.base.Strings;
import com.xk.sport.backend.dao.repository.LessonDao;
import com.xk.sport.backend.common.entity.LessonQuery;
import com.xk.sport.backend.dao.model.Lesson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Service
public class LessonService {
    @Autowired
    private LessonDao lessonDao;

    public Page<Lesson> findAllByQuery(final LessonQuery query) {
        Pageable pageable = new PageRequest(query.getPageNum(), query.getSize(), 0 == query.getSortAsc() ? Sort.Direction.DESC : Sort.Direction.ASC, query.getSortKey());
        Page<Lesson> page = lessonDao.findAll(new Specification<Lesson>() {
            @Override
            public Predicate toPredicate(Root<Lesson> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> list = new ArrayList<Predicate>();
                if (!Strings.isNullOrEmpty(query.getName())) {
                    list.add(criteriaBuilder.like(root.get("name").as(String.class), "%" + query.getName() + "%"));
                }
                return criteriaBuilder.and(list.toArray(new Predicate[0]));
            }
        }, pageable);
        return page;
    }

    public List<Lesson> findAll() {
        return lessonDao.findAll();
    }

    public Lesson findOne(long id) {
        return lessonDao.findOne(id);
    }

    public Lesson add(Lesson lesson) {
        if (lesson == null || lesson.getId() > 0) {
            return null;
        }
        lesson.setCreateTime(System.currentTimeMillis());
        return lessonDao.save(lesson);
    }

    public Lesson update(Lesson lesson) {
        if (lesson == null || lesson.getId() <= 0) {
            return null;
        }
        return lessonDao.save(lesson);
    }

    public boolean delete(long id) {
        lessonDao.delete(id);
        return true;
    }
}
